﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TMS_Master.RabbitMQ
{
    public class MQController: ControllerBase
    {
        [Route("api/Mq/order")]
        [HttpGet]
        /// <summary>
        /// 生产者
        /// </summary>
        public void order()
        {
            //连接（这个就相当于数据库连接字符串一样）
            var factory = new ConnectionFactory() { HostName = "localhost", UserName = "guest", Password = "guest", Port = 5672 };
            //创建连接
            using (var connction = factory.CreateConnection())
            {
                //创建消息管道
                using (var channel = connction.CreateModel())
                {
                    //声明队列
                    channel.QueueDeclare(queue: "采购", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    //消息
                    string message = JsonConvert.SerializeObject("货物名称:轮胎,申请人:李晓红");
                    //编码
                    var body = Encoding.UTF8.GetBytes(message);
                    //发布一条消息到MQ
                    channel.BasicPublish(exchange: "", routingKey: "采购", basicProperties: null, body: body);
                }

            }
        }



        [Route("api/Mq/Receiver")]
        [HttpGet]
        /// <summary>
        /// 消费者
        /// </summary>
        /// <returns></returns>
        public void Receiver()
        {
            //定义变量
            string data1 = "";
            //连接
            var factory = new ConnectionFactory() { HostName = "localhost", UserName = "guest", Password = "guest", Port = 5672 };
            //创建连接
            using (var connction = factory.CreateConnection())
            {
                //创建消息管道
                using (var channel = connction.CreateModel())
                {
                    //声明一个队列（这个队列必须和发布者队列一致）
                    channel.QueueDeclare(queue: "采购", durable: false, exclusive: false, autoDelete: false, arguments: null);

                    //获取RabbitMq一条数据
                    BasicGetResult result = channel.BasicGet("采购", true);

                    //将数据进行编码
                    string data = Encoding.UTF8.GetString(result.Body.ToArray());
                    data1 += data;

                }
            }

        }
    }
}
